<template>
  <div class="course-detail-page">
    <!-- 面包屑导航 -->
    <div class="course-breadcrumb">
      <div class="breadcrumb-content">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/course' }">课程中心</el-breadcrumb-item>
          <el-breadcrumb-item>{{ course.title }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>

    <div class="main-container">
      <div class="main-content">
        <!-- 标题部分 -->
        <div class="title-section">
          <div class="course-header">
            <div class="course-info">
              <h1>{{ course.title }}</h1>
              <div class="course-brief">
                <div class="brief-item">
                  <el-icon>
                    <User />
                  </el-icon>
                  <span>讲师：{{ course.teacher }}</span>
                </div>
                <div class="brief-item">
                  <el-icon>
                    <Calendar />
                  </el-icon>
                  <span>开课时间：{{ course.schedule }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 课程内容和目录部分 -->
        <div class="content-section">
          <!-- 左侧视频区域 -->
          <div class="video-section">
            <div class="video-container">
              <video ref="videoPlayer" :src="currentVideo" class="video-player" controls preload="none"
                :autoplay="false" muted>
              </video>
            </div>
            <!-- 视频下方的交互按钮 -->
            <div class="video-actions">
              <div class="action-buttons">
                <el-button :type="course.is_favorited ? 'success' : 'default'" @click="handleFavorite">
                  <el-icon>
                    <Star />
                  </el-icon>
                  {{ course.is_favorited ? '已收藏' : '收藏课程' }}
                </el-button>

                <el-button :type="course.is_liked ? 'warning' : 'default'" @click="handleLike">
                  <el-icon>
                    <Sunny />
                  </el-icon>
                  {{ course.is_liked ? '已点赞' : '点赞课程' }}
                </el-button>

                <el-button type="info" @click="handleShare">
                  <el-icon>
                    <Share />
                  </el-icon>
                  分享课程
                </el-button>
              </div>
              <div class="video-stats">
                <span class="stat-item">
                  <el-icon>
                    <Star />
                  </el-icon>
                  {{ course.favorites_count || 0 }} 收藏
                </span>
                <span class="stat-item">
                  <el-icon>
                    <Sunny />
                  </el-icon>
                  {{ course.likes_count || 0 }} 点赞
                </span>
                <span class="stat-item">
                  <el-icon>
                    <View />
                  </el-icon>
                  {{ course.views || 0 }} 观看
                </span>
              </div>
            </div>
          </div>

          <!-- 右侧目录区域 -->
          <div class="catalog-section">
            <h2>课程目录</h2>
            <ul class="catalog-list">
              <li v-for="(chapter, index) in courseChapters" :key="index" :class="{ active: currentChapter === index }"
                @click="selectChapter(index)">
                <div class="video-info">
                  <span class="video-index">{{ index + 1 }}</span>
                  <div class="video-detail">
                    <div class="video-title">第{{ index + 1 }}章：{{ chapter.title }}</div>
                    <div class="video-duration">{{ chapter.duration || '20分钟' }}</div>
                  </div>
                </div>
                <el-icon v-if="currentChapter === index">
                  <ArrowRight />
                </el-icon>
              </li>
            </ul>
          </div>
        </div>

        <!-- 课程介绍部分 -->
        <div class="course-intro">
          <div class="section-header">
            <h2>课程介绍</h2>
            <div class="divider"></div>
          </div>
          <div class="intro-content">
            <div class="intro-text">{{ course.description }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  User,
  Calendar,
  Star,
  Collection,
  Share,
  ArrowLeft,
  Timer,
  Document,
  VideoPlay,
  ChatDotRound,
  DataLine,
  Plus,
  Sunny,
  View,
  ArrowRight,
} from '@element-plus/icons-vue'
import { enrollCourse, getCourseDetail, likeCourse, favoriteCourse } from '@/api/courses'

const route = useRoute()
const courseId = route.params.id
const course = ref({})
const loading = ref(true)

// 获取课程详情
const fetchCourseDetail = async () => {
  loading.value = true
  try {
    const { data } = await getCourseDetail(courseId)
    console.log('获取到的课程详情:', data)
    course.value = {
      ...data,
      isRegistered: data.is_registered === 1 // 将数字转换为布尔值
    }
    console.log('处理后的课程状态:', course.value)
  } catch (error) {
    console.error('获取课程详情失败:', error)
    ElMessage.error('获取课程详情失败')
  } finally {
    loading.value = false
  }
}

// 点赞
const handleLike = async () => {
  try {
    await likeCourse(courseId)
    await fetchCourseDetail()
    ElMessage.success(course.value.is_liked ? '取消点赞成功' : '点赞成功')
  } catch (error) {
    console.error('点赞失败:', error)
    ElMessage.error('操作失败')
  }
}

// 收藏
const handleFavorite = async () => {
  try {
    await favoriteCourse(courseId)
    await fetchCourseDetail()
    ElMessage.success(course.value.is_favorited ? '取消收藏成功' : '收藏成功')
  } catch (error) {
    console.error('收藏失败:', error)
    ElMessage.error('操作失败')
  }
}

// 分享
const handleShare = () => {
  if (navigator.clipboard) {
    navigator.clipboard.writeText(course.value.share_url)
    ElMessage.success('链接已复制到剪贴板')
  } else {
    ElMessage.error('您的浏览器不支持自动复制')
  }
}

// 报名课程
const handleEnroll = async () => {
  try {
    await enrollCourse(courseId)
    ElMessage.success('报名成功')
    await fetchCourseDetail()
    console.log('报名后的课程状态:', course.value)
  } catch (error) {
    console.error('报名失败:', error)
    ElMessage.error(error.response?.data?.message || '报名失败')
  }
}

// 添加课程章节数据
const courseChapters = ref([
  { title: '课程介绍', duration: '15分钟', video_url: '' },
  { title: '基础知识', duration: '30分钟', video_url: '' },
  { title: '核心内容', duration: '45分钟', video_url: '' },
  { title: '实践应用', duration: '30分钟', video_url: '' }
])

const currentChapter = ref(0)
const currentVideo = computed(() => {
  if (!course.value.video_url) return ''
  const videoUrls = JSON.parse(course.value.video_url)
  // 如果视频数组存在且有对应章节的视频，返回对应视频
  if (videoUrls && videoUrls[currentChapter.value]) {
    return 'http://localhost:3000' + videoUrls[currentChapter.value]
  }
  // 否则返回第一个视频
  return videoUrls.length > 0 ? 'http://localhost:3000' + videoUrls[0] : ''
})

const selectChapter = (index) => {
  currentChapter.value = index
  // 获取视频元素
  const videoPlayer = document.querySelector('.video-player')
  if (videoPlayer) {
    // 更新视频源后重新加载
    videoPlayer.load()
    // 可选：自动播放
    // videoPlayer.play()
  }
  console.log('切换到章节:', index + 1, '视频URL:', currentVideo.value)
}

onMounted(() => {
  fetchCourseDetail()
})
</script>

<style scoped>
.course-detail-page {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.course-breadcrumb {
  background: white;
  padding: 16px 0;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.breadcrumb-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.main-container {
  max-width: 1200px;
  margin: 24px auto;
  padding: 0 20px;
}

/* 标题部分样式 */
.title-section {
  background: white;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.course-header {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 视频和目录部分样式 */
.content-section {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 24px;
  margin-bottom: 24px;
}

.video-section {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.video-container {
  width: 100%;
  padding-top: 56.25%;
  /* 16:9 宽高比 */
  position: relative;
  background: #000;
  border-radius: 8px;
  overflow: hidden;
}

.video-player {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: contain;
}

/* 视频下方按钮样式 */
.video-actions {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .content-section {
    grid-template-columns: 1fr;
  }

  .video-container {
    padding-top: 75%;
    /* 4:3 宽高比，更适合移动端 */
  }
}

/* 目录列表样式 */
.catalog-list {
  margin-top: 20px;
}

.catalog-list li {
  padding: 12px 15px;
  margin-bottom: 10px;
  background: #fff;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border: 1px solid #ebeef5;
}

.catalog-list li:hover {
  background: #f0f7ff;
  transform: translateX(5px);
}

.catalog-list li.active {
  background: #e6f7ff;
  border-color: #1890ff;
}

.video-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.video-index {
  width: 24px;
  height: 24px;
  background: #f0f0f0;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #666;
}

.video-detail {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.video-title {
  font-size: 14px;
  color: #333;
}

.video-duration {
  font-size: 12px;
  color: #999;
}

.course-intro {
  background: white;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.section-header {
  text-align: center;
  margin-bottom: 24px;
}

.section-header h2 {
  font-size: 1.8em;
  color: #2c3e50;
  margin-bottom: 16px;
}

.divider {
  width: 60px;
  height: 4px;
  background: var(--el-color-primary);
  margin: 0 auto;
  border-radius: 2px;
}

.intro-content {
  max-width: 800px;
  margin: 0 auto;
}

.intro-text {
  color: #666;
  line-height: 1.8;
  font-size: 16px;
  text-align: justify;
  padding: 0 20px;
}
</style>
